import type Draw from '.';

export type PointFeature = GeoJSON.Feature<GeoJSON.Point>;
export type LineFeature = GeoJSON.Feature<GeoJSON.LineString>;

export class ShapeTool {
  protected draw: Draw | undefined;

  // TODO 正常应该在get feature的properties中添加
  // 但是这里没有办法设置properties，所以只能在这里添加
  // userProperties: true,没有起作用
  // TODO 尝试setFeatureProperty?
  protected shapeIds: string[] = [];

  constructor(draw: Draw) {
    this.draw = draw;
  }

  createLabels = (
    id: string,
    texts: string[],
    coords: GeoJSON.Position[],
    offset: [number, number] | undefined = undefined,
  ) => {
    if (!this.draw?.map) return;
    const _id = `dzmap-draw-label-${id}`;
    const lblColl = {
      type: 'FeatureCollection',
      features: texts.map((text, index) => ({
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates: coords[index],
        },
        properties: {
          text,
        },
      })),
    };
    this.draw.map.addSource(_id, {
      type: 'geojson',
      data: lblColl as unknown as GeoJSON.GeoJSON,
    });
    this.draw.map.addLayer({
      id: _id,
      source: _id,
      type: 'symbol',
      layout: {
        'text-field': ['get', 'text'],
        'text-size': 14,
        'text-offset': offset || [0, -1],
      },
      paint: {
        'text-color': '#ff00ff',
      },
    });
    return lblColl;
  };

  addId = (id: string) => {
    if (!this.shapeIds.includes(id)) {
      this.shapeIds.push(id);
    }
  };

  delId = (id: string) => {
    if (this.shapeIds.includes(id)) {
      this.shapeIds = this.shapeIds.filter((_id) => _id !== id);
    }
  };
}
